package com.haitao.wavebbs.service;

import com.haitao.wavebbs.dao.PostRepository;
import com.haitao.wavebbs.entity.Post;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

@Service
public class PostService {

    public final PostRepository postRepository;

    public PostService(PostRepository postRepository) {
        this.postRepository = postRepository;
    }

    /**
     * 创建帖子
     *    前端字段检测：postName不为空
     *    服务器插入字段：createdTime、userId(解析token获取)
     *    插入字符长度：
     * @param post
     * @return  创建的帖子的postId
     */
    public int createPost(Post post) throws Exception {
        if (post.getPostName()==null){
            throw new Exception("标题不能为空");
        }
        Timestamp currentSystemTimeStamp = new Timestamp(System.currentTimeMillis());
        post.setCreatedTime(currentSystemTimeStamp);
        post.setUpdatedTime(currentSystemTimeStamp);
        Post save = postRepository.save(post);
        return save.getPostId();
    }

    /**
     * 获取post总数，用于分页
     * @return int:postAmount
     */
    public int getPostAmount(){
        int postAmount = postRepository.getPostAmount();
        return postAmount;
    }

    /**
     * getPosts方式一：根据off=page*per_page，来查询post
     * @param per_page
     * @param pageNumber
     * @param userId
     * @return
     */
    public  List<Post>  getPosts(int per_page,int pageNumber,Integer userId){
        int offset=(pageNumber)*per_page;
        List<Post> posts=null;
        if(userId == null){
            posts = postRepository.getPosts(per_page, offset);
        }else {
            posts = postRepository.getPostsByUserId(per_page, pageNumber*per_page, userId);
        }
        return posts;
    }



    /**
     * getPosts方式2：根据updatedTime作为查询条件，来查询post。对于大数据量，方式2比方式1查询快，
     * 四种可能：无userId+下页 ； 无userId+上页; 有userId+下页；有userId+上页
     * @param per_page
     * @param updatedTime
     * @param userId
     * @return
     */
    public  List<Post>  getPosts(int per_page,String updatedTime,int lastOrNext,int userId){
        List<Post> posts=null;
        if(userId<=0){
            if (lastOrNext<=0){
                posts = postRepository.getPostsPreviousPage(per_page,updatedTime,Math.abs(lastOrNext));
            }else{
                posts = postRepository.getPostsNextPage(per_page,updatedTime,Math.abs(lastOrNext));
            }
        }else {
            if (lastOrNext<=0){
                posts = postRepository.getPostsByUserIdPreviousPage(per_page,updatedTime,Math.abs(lastOrNext),userId);
            }else{
                posts = postRepository.getPostsByUserIdNextPage(per_page,updatedTime,Math.abs(lastOrNext),userId);
            }
        }
        return posts;
    }


    /**
     * 通过postId获取某一条post的基本信息
     * @param postId
     * @return
     */
    public  Post  getPostByPostId(int postId){
        Post postByPostId = postRepository.getPostByPostId(postId);
        return postByPostId;
    }

}
